package com.hbnu.system.service.impl;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hbnu.system.config.BaseException;
import com.hbnu.system.constant.RoleConstant;
import com.hbnu.system.constant.StatusCheckConstant;
import com.hbnu.system.core.base.CommonPage;
import com.hbnu.system.mapper.PaperMapper;
import com.hbnu.system.model.context.BaseContext;
import com.hbnu.system.model.dto.CheckBackDTO;
import com.hbnu.system.model.dto.PaperDTO;
import com.hbnu.system.model.dto.PaperTSdto;
import com.hbnu.system.model.entity.*;
import com.hbnu.system.model.query.PaperPageQuery;
import com.hbnu.system.model.vo.PaperVO;
import com.hbnu.system.service.*;
import com.hbnu.system.utils.CheckAuditHelper;
import com.hbnu.system.utils.CheckRoleUtil;
import com.hbnu.system.utils.UserInfoUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.time.LocalDateTime;
import java.util.Arrays;
import java.util.List;
import java.util.Objects;
import java.util.UUID;
import java.util.stream.Collectors;

/**
 * <p>
 * 论文服务实现类
 * 处理论文的增删改查、审核流程以及相关业务逻辑
 * </p>
 *
 * @author ${author}
 * @since 2023-05-16
 */
@Service
@Slf4j
public class PaperServiceImpl extends ServiceImpl<PaperMapper, Paper> implements IPaperService {

    @Autowired
    private IPaperService iPaperService;

    @Autowired
    private IPaperauthorService iPaperauthorService;

    @Autowired
    private IUserService iUserService;

    @Autowired
    private AuditService auditService;

    @Autowired
    private IdToStatsService idToStatsService;

    @Autowired
    private IPaperfileService iPaperfileService;

    @Autowired
    private IPaperprojectService iPaperprojectService;

    @Autowired
    private IPaperQualificationService iPaperQualificationService;

    @Autowired
    private CheckRoleUtil checkRoleUtil;

    @Autowired
    private PaperMapper paperMapper;

    @Autowired
    private UserInfoUtils userInfoUtils;

    @Autowired
    private CheckAuditHelper checkAuditHelper ;



    /**
     * 论文查重功能
     * 检查论文名称是否已存在
     * @param paper_name 论文名称
     * @return 不存在返回true，存在则抛出异常
     */
    @Override
    public boolean checkPaperName(String paper_name) {
        Paper one = super.getOne(Wrappers.lambdaQuery(Paper.class)
                .eq(Paper::getPaperName, paper_name));
        if (Objects.nonNull(one)) {
            throw new BaseException("该论文名称已存在!");
        }
        return true;
    }

    /**
     * 提交论文审核
     * 将论文状态改为待院级审核
     * @param id 论文ID
     * @return 操作结果
     */
    @Override
    public Boolean ReCommitPaper(String id) {
        Paper paper = super.getOne(Wrappers.lambdaQuery(Paper.class).eq(Paper::getPaperID, id));
        //检查论文字段是否填写完整
        checkPaper(paper);
        paper.setStatus("待院级审核");
        paper.setReason("");

        return baseMapper.updateById(paper) == 1;
    }

    /**
     * 添加论文
     * 验证论文信息并保存到数据库
     * @param paperdto 论文DTO对象
     * @return 添加结果
     */
    @Override
    public boolean addPaper(PaperDTO paperdto) {
        // 参数校验
        if (StrUtil.isEmpty(paperdto.getPaperCate()) || StrUtil.isBlank(paperdto.getPaperCate())) {
            throw new BaseException("请输入论文分类");
        }
        if (StrUtil.isEmpty(paperdto.getEntered()) || StrUtil.isBlank(paperdto.getEntered())) {
            throw new BaseException("请输入录入人");
        }
        if (StrUtil.isEmpty(paperdto.getPaperName()) || StrUtil.isBlank(paperdto.getPaperName())) {
            throw new BaseException("请输入论文名称");
        }
        checkPaperName(paperdto.getPaperName());
        if (StrUtil.isEmpty(paperdto.getPeriodicalName()) || StrUtil.isBlank(paperdto.getPeriodicalName())) {
            throw new BaseException("请输入刊物名称");
        }
        if (StrUtil.isEmpty(paperdto.getPeriodicalCate()) || StrUtil.isBlank(paperdto.getPeriodicalCate())) {
            throw new BaseException("请输入刊物分类");
        }

        // 被动查看论文名称是否重复
        Paper one1 = super.getOne(Wrappers.lambdaQuery(Paper.class)
                .eq(Paper::getPaperName, paperdto.getPaperName()));
        if (Objects.nonNull(one1) && !(one1.getPaperID().equals(paperdto.getPaperID()))) {
            throw new BaseException("论文名称重复!");
        }
        paperdto.setStatus("草稿");
        paperdto.setEnteredDate(LocalDateTime.now());
        paperdto.setAssessment(0);
        Paper paper = new Paper();
        BeanUtils.copyProperties(paperdto, paper);
        return baseMapper.insert(paper) == 1;
    }

    /**
     * 删除论文
     * 级联删除论文相关的作者、项目、文件等信息
     * @param PID 论文ID
     * @return 删除结果
     * @throws IOException 删除文件时可能抛出的异常
     */
    @Override
    public boolean deletePaper(String PID) throws IOException {
        Paper one = super.getOne(Wrappers.lambdaQuery(Paper.class)
                .eq(Paper::getPaperID, PID));
        if (Objects.isNull(one)) {
            throw new BaseException("论文编号有误!");
        }
        checkRoleUtil.checkPermissionAchievement(one.getStatus());

        // 删除论文关联的作者
        iPaperauthorService.remove(Wrappers.lambdaQuery(Paperauthor.class)
                .eq(Paperauthor::getPaperID, PID));

        // 删除论文关联的项目
        iPaperprojectService.remove(Wrappers.lambdaQuery(Paperproject.class)
                .eq(Paperproject::getPaperID, PID));

        // 删除论文关联的量化分数
        iPaperQualificationService.remove(Wrappers.lambdaQuery(Paper_Qualification.class)
                .eq(Paper_Qualification::getPaperID, PID));

        // 删除文件信息
        List<Paperfile> paperFiles = iPaperfileService.list(Wrappers.lambdaQuery(Paperfile.class)
                .eq(Paperfile::getPaperid, PID));
        List<String> ids = paperFiles.stream().map(Paperfile::getFileid).collect(Collectors.toList());
        for (String id : ids) {
            iPaperfileService.deletPaperfile(id);
        }

        // 删除审核记录
        auditService.remove(Wrappers.lambdaQuery(Audit.class)
                .eq(Audit::getSynthesisID, PID));

        return baseMapper.deleteById(PID) == 1;
    }

    /**
     * 根据ID获取论文
     * @param paperID 论文ID
     * @return 论文实体
     */
    @Override
    public Paper getPaper(String paperID) {
        Paper paper = paperMapper.selectById(paperID);
        if (Objects.isNull(paper)) {
            throw new BaseException("论文编号异常!未查找到该论文");
        }

        return paper;
    }

    /**
     * 根据ID获取论文DTO
     * 包含额外的作者、部门等信息
     * @param paperID 论文ID
     * @return 论文DTO对象
     */
    @Override
    public PaperDTO getPaperDTOById(String paperID) {
        Paper paper = super.getOne(Wrappers.lambdaQuery(Paper.class)
                .eq(Paper::getPaperID, paperID));
        if (Objects.isNull(paper)) {
            throw new BaseException("论文编号异常!未查找到该论文");
        }

        String entered = idToStatsService.IdToName(paper.getEntered());
        String dept = idToStatsService.IdToDept(paper.getDept());
        String allauthor = idToStatsService.IdToAllauthor(paper.getAllAuthor());

        PaperDTO paperdto = new PaperDTO();
        BeanUtils.copyProperties(paper, paperdto);

        paperdto.setAllAuthorName(allauthor);
        paperdto.setEnteredName(entered);
        paperdto.setDeptName(dept);

        return paperdto;
    }

    /**
     * 修改论文
     * 验证并更新论文信息
     * @param paper 论文实体
     * @return 修改结果
     */
    @Override
    public boolean updatePaper(Paper paper) {
        checkRoleUtil.checkPermissionAchievement(paper.getStatus());

        // 参数校验
        if (StrUtil.isEmpty(paper.getPaperCate()) || StrUtil.isBlank(paper.getPaperCate())) {
            throw new BaseException("请输入论文分类");
        }
        if (StrUtil.isEmpty(paper.getEntered()) || StrUtil.isBlank(paper.getEntered())) {
            throw new BaseException("请输入录入人");
        }
        if (StrUtil.isEmpty(paper.getPaperName()) || StrUtil.isBlank(paper.getPaperName())) {
            throw new BaseException("请输入论文名称");
        }

        Paper one = iPaperService.getOne(Wrappers.lambdaQuery(Paper.class)
                .eq(Paper::getPaperName, paper.getPaperName())
                .ne(Paper::getPaperID, paper.getPaperID()));

        if (Objects.nonNull(one)) {
            throw new BaseException("该论文名称已存在!");
        }

        if (StrUtil.isEmpty(paper.getPeriodicalName()) || StrUtil.isBlank(paper.getPeriodicalName())) {
            throw new BaseException("请输入刊物名称");
        }
        if (StrUtil.isEmpty(paper.getPeriodicalCate()) || StrUtil.isBlank(paper.getPeriodicalCate())) {
            throw new BaseException("请输入刊物分类");
        }
        return baseMapper.updateById(paper) == 1;
    }

    /**
     * 学院审核通过
     * 根据当前用户角色确定下一步状态
     * @param token 用户token
     * @param PID 论文ID
     * @return 审核结果
     */
    @Override
    public Boolean collegeCheckPass(String token, String PID) {
        Paper paper = query().eq("PaperID", PID).one();
        if (paper == null) throw new BaseException("该论文编号有误!");

        String roleName = userInfoUtils.getCurrentUserInfo().getRoleName();
        // 目标状态
        String targetStatus = StatusCheckConstant.COLLEGE_CHECK_PEOPLE.equals(roleName)
                ? StatusCheckConstant.WAIT_SCHOOL_CHECK
                : StatusCheckConstant.CHECK_PASS;

        return checkAuditHelper.doPassAudit(
                paper,
                StatusCheckConstant.WAIT_COLLEGE_CHECK,
                targetStatus,
                roleName,
                "论文",
                paper::getPaperID,
                paper::getStatus,
                paper::setStatus,
                this::updatePaperByEntity
        );
    }

    /**
     * 学院审核退回
     * @param token 用户token
     * @param checkBackDTO 退回DTO
     * @return 退回结果
     */
    @Override
    public Boolean collegeCheckBack(String token, CheckBackDTO checkBackDTO) {
        Paper paper = query().eq("PaperID", checkBackDTO.getID()).one();
        if (paper == null) throw new BaseException("该论文编号有误!");

        String roleName = userInfoUtils.getCurrentUserInfo().getRoleName();
        String backStatus = StatusCheckConstant.COLLEGE_CHECK_PEOPLE.equals(roleName)
                ? StatusCheckConstant.COLLEGE_CHECK_BACK
                : StatusCheckConstant.SCHOOL_CHECK_BACK;

        return checkAuditHelper.doBackAudit(
                paper,
                StatusCheckConstant.WAIT_COLLEGE_CHECK,
                backStatus,
                checkBackDTO.getReason(),
                "论文",
                paper::getPaperID,
                paper::getStatus,
                paper::setStatus,
                paper::setReason,
                this::updatePaperByEntity
        );
    }

    /**
     * 学校审核通过
     * @param token 用户token
     * @param PID 论文ID
     * @return 审核结果
     */
    @Override
    public Boolean schoolCheckPass(String token, String PID) {
        Paper paper = query().eq("PaperID", PID).one();
        if (paper == null) throw new BaseException("该论文编号有误!");

        String currentStatus = paper.getStatus();
        if (!StatusCheckConstant.WAIT_SCHOOL_CHECK.equals(currentStatus)
                && !StatusCheckConstant.WAIT_COLLEGE_CHECK.equals(currentStatus)) {
            throw new BaseException("该论文状态不处于该环节!");
        }

        String roleName = userInfoUtils.getCurrentUserInfo().getRoleName();

        return checkAuditHelper.doPassAudit(
                paper,
                currentStatus, // 当前状态可为学院或学校待审核
                StatusCheckConstant.CHECK_PASS,
                roleName,
                "论文",
                paper::getPaperID,
                paper::getStatus,
                paper::setStatus,
                this::updatePaperByEntity
        );
    }

    /**
     * 学校审核退回
     * @param token 用户token
     * @param checkBackDTO 退回DTO
     * @return 退回结果
     */
    @Override
    public Boolean schoolCheckBack(String token, CheckBackDTO checkBackDTO) {
        Paper paper = query().eq("PaperID", checkBackDTO.getID()).one();
        if (paper == null) throw new BaseException("该论文编号有误!");

        String currentStatus = paper.getStatus();
        if (!StatusCheckConstant.WAIT_SCHOOL_CHECK.equals(currentStatus)
                && !StatusCheckConstant.WAIT_COLLEGE_CHECK.equals(currentStatus)
                && !StatusCheckConstant.CHECK_PASS.equals(currentStatus)) {
            throw new BaseException("该论文状态不处于该环节!");
        }

        String roleName = userInfoUtils.getCurrentUserInfo().getRoleName();

        return checkAuditHelper.doBackAudit(
                paper,
                currentStatus,
                StatusCheckConstant.SCHOOL_CHECK_BACK,
                checkBackDTO.getReason(),
                "论文",
                paper::getPaperID,
                paper::getStatus,
                paper::setStatus,
                paper::setReason,
                this::updatePaperByEntity
        );
    }

    /**
     * 用户查看分页论文
     * 根据用户角色返回不同的论文列表
     * @param paperPageQuery 查询参数
     * @return 分页数据
     */
    @Override
    public CommonPage<PaperVO> userGetPapers(PaperPageQuery paperPageQuery) {
        String userId = BaseContext.getCurrentId();
        log.info("从BaseContext获取的userId：{}", userId); // 打印获取到的userId
        User user = iUserService.getById(userId);
        String role = user.getRole();

        // 创建MyBatis-Plus的Page对象
        Page<PaperVO> page = new Page<>(paperPageQuery.getPageNum(), paperPageQuery.getPageSize());
        IPage<PaperVO> paperIPage = null;

        // 根据角色执行不同查询
        if (role.equals(RoleConstant.ROLE_ADMIN_SCHOOL)) {
            paperIPage = paperMapper.schoolGetRelatePaperQuery(page, paperPageQuery, user);
        } else if (role.equals(RoleConstant.ROLE_ADMIN_COLLEGE)) {
            paperIPage = paperMapper.collegeGetRelatePaperQuery(page, paperPageQuery, user);
        } else {
            paperIPage = paperMapper.userGetRelatePaperQuery(page, paperPageQuery, user);
        }

        // 初始化量化分数
        float figure = 0;
        List<PaperVO> records = paperIPage.getRecords();

        // 遍历记录，计算量化分数并设置allAuthorName为录入人姓名【作者属性】
        for (PaperVO record : records) {
            if (record.getStatus().equals(StatusCheckConstant.CHECK_PASS)) {
                figure += record.getScore();
            }
            
            // 获取录入人信息并设置allAuthorName为录入人姓名【作者属性】
            Paper paper = iPaperService.getOne(Wrappers.lambdaQuery(Paper.class)
                    .eq(Paper::getPaperID, record.getPaperID()));
            if (paper != null && StrUtil.isNotEmpty(paper.getEntered())) {
                User enteredUser = iUserService.getById(paper.getEntered());
                if (enteredUser != null) {
                    // 查询录入人的作者信息，获取作者属性
                    Paperauthor enteredAuthor = iPaperauthorService.getOne(
                            Wrappers.lambdaQuery(Paperauthor.class)
                                    .eq(Paperauthor::getPaperID, record.getPaperID())
                                    .eq(Paperauthor::getUserAccount, enteredUser.getAccount())
                    );
                    
                    // 按照"姓名【作者属性】"格式设置，如果作者属性为空则只显示姓名
                    if (enteredAuthor != null && StrUtil.isNotEmpty(enteredAuthor.getAuthortype())) {
                        record.setAllAuthorName(enteredUser.getName() + "【" + enteredAuthor.getAuthortype() + "】");
                    } else {
                        record.setAllAuthorName(enteredUser.getName());
                    }
                }
            }
        }

        // 构造返回分页对象
        CommonPage<PaperVO> paperCommonPage = CommonPage.restPage(paperIPage);
        paperCommonPage.setFigure(figure);
        paperCommonPage.setList(records);

        return paperCommonPage;
    }

    /**
     * 导出论文数据
     * @param paperPageQuery 查询条件
     * @return 导出数据
     */
    @Override
    public CommonPage<Paper> export(PaperPageQuery paperPageQuery) {
        String userId = BaseContext.getCurrentId();
        User user = iUserService.getById(userId);
        String role = user.getRole();

        // 创建MyBatis-Plus的Page对象
        Page<Paper> page;
        
        // 判断是否全部导出
        if (Boolean.TRUE.equals(paperPageQuery.getExportAll())) {
            // 全部导出：先查询符合条件的总数
            long total = 0;
            if (role.equals(RoleConstant.ROLE_ADMIN_SCHOOL)) {
                total = paperMapper.schoolExportRelatePaperQuery(
                    new Page<>(1, 1), paperPageQuery, user).getTotal();
            } else if (role.equals(RoleConstant.ROLE_ADMIN_COLLEGE)) {
                total = paperMapper.collegeExportRelatePaperQuery(
                    new Page<>(1, 1), paperPageQuery, user).getTotal();
            } else {
                total = paperMapper.userExportRelatePaperQuery(
                    new Page<>(1, 1), paperPageQuery, user).getTotal();
            }
            
            // 数据量限制检查
            if (total > 10000) {
                throw new BaseException("导出数据量过大（超过10000条），请缩小筛选范围后重试！");
            }
            
            // 设置分页大小为总数，实现一次性查询全部
            page = new Page<>(1, total > 0 ? (int) total : 1);
            log.info("全部导出模式，共{}条数据", total);
        } else {
            // 分页导出：使用传入的分页参数
            page = new Page<>(paperPageQuery.getPageNum(), paperPageQuery.getPageSize());
            log.info("分页导出模式，第{}页，每页{}条", paperPageQuery.getPageNum(), paperPageQuery.getPageSize());
        }

        IPage<Paper> paperIPage = null;

        // 根据角色执行不同查询
        if (role.equals(RoleConstant.ROLE_ADMIN_SCHOOL)) {
            paperIPage = paperMapper.schoolExportRelatePaperQuery(page, paperPageQuery, user);
        } else if (role.equals(RoleConstant.ROLE_ADMIN_COLLEGE)) {
            paperIPage = paperMapper.collegeExportRelatePaperQuery(page, paperPageQuery, user);
        } else {
            paperIPage = paperMapper.userExportRelatePaperQuery(page, paperPageQuery, user);
        }

        // 初始化量化分数
        float figure = 0;
        List<Paper> records = paperIPage.getRecords();

        // 遍历记录，计算量化分数并设置关联信息
        for (Paper record : records) {
            if (record.getStatus().equals(StatusCheckConstant.CHECK_PASS)) {
                figure += record.getScore();
            }

            // 设置第一作者和共同第一作者
            List<Paperauthor> LeadAuthors = iPaperauthorService.list(Wrappers.lambdaQuery(Paperauthor.class)
                    .eq(Paperauthor::getPaperID, record.getPaperID())
                    .in(Paperauthor::getAuthortype, Arrays.asList("第一作者", "共同第一作者")));
            record.setLeadAuthor(LeadAuthors.stream().map(Paperauthor::getName).collect(Collectors.joining(",")));

            // 设置通讯作者
            List<Paperauthor> ContactAuthors = iPaperauthorService.list(Wrappers.lambdaQuery(Paperauthor.class)
                    .eq(Paperauthor::getPaperID, record.getPaperID())
                    .eq(Paperauthor::getAuthortype, "通讯作者"));
            record.setCorrespondingAuthor(ContactAuthors.stream().map(Paperauthor::getName).collect(Collectors.joining(",")));

            // 设置关联项目
            List<Paperproject> paperProjects = iPaperprojectService.list(Wrappers.lambdaQuery(Paperproject.class)
                    .eq(Paperproject::getPaperID, record.getPaperID()));
            record.setAssociatedProjects(paperProjects.stream().map(Paperproject::getProjectName).collect(Collectors.joining(",")));
        }

        // 构造返回分页对象
        CommonPage<Paper> paperCommonPage = CommonPage.restPage(paperIPage);
        paperCommonPage.setFigure(figure);
        paperCommonPage.setList(records);

        return paperCommonPage;
    }
    
    @Override
    public boolean saveDraftPaper(PaperTSdto paperTSdto) {
        // 创建Paper实体对象
        Paper paper = new Paper();
        // 复制属性
        BeanUtils.copyProperties(paperTSdto, paper);
        
        // 设置录入日期
        if (paper.getEnteredDate() == null) {
            paper.setEnteredDate(LocalDateTime.now());
        }
        
        // 设置状态为草稿（如果未设置）
        if (StrUtil.isEmpty(paper.getStatus())) {
            paper.setStatus("草稿");
        }
        
        // 处理ID：如果有ID则更新，无ID则新增
        if (StrUtil.isNotEmpty(paper.getPaperID())) {
            // 检查论文是否存在
            Paper existingPaper = this.getById(paper.getPaperID());
            if (existingPaper != null) {
                // 更新论文
                return this.updateById(paper);
            } else {
                // 论文不存在，进行新增
                return this.save(paper);
            }
        } else {
            // 使用雪花算法生成新的PaperID，并确保长度不超过20字符以适应varchar(20)类型
            String snowflakeId = String.valueOf(IdWorker.getId());
            paper.setPaperID(snowflakeId);
            // 新增论文
            return this.save(paper);
        }
    }

    /**
     * 更新论文实体
     * @param paper 论文实体
     * @return 更新结果
     */
    private Boolean updatePaperByEntity(Paper paper) {
        return baseMapper.updateById(paper) == 1;
    }

    /**
     * 撤回论文
     * 只有在院级审核状态才能撤回，撤回后状态变为草稿
     * @param id 论文ID
     * @return 操作结果
     */
    @Override
    public Boolean withdrawPaper(String id) {
        // 从BaseContext获取当前用户ID
        String userId = BaseContext.getCurrentId();
        log.info("从BaseContext获取的userId：{}", userId); // 打印获取到的userId
        
        // 获取用户对象
        User user = iUserService.getById(userId);
        if (Objects.isNull(user)) {
            throw new BaseException("用户不存在！");
        }
        
        // 获取论文信息
        Paper paper = super.getOne(Wrappers.lambdaQuery(Paper.class).eq(Paper::getPaperID, id));
        if (Objects.isNull(paper)) {
            throw new BaseException("论文编号有误!");
        }
        
        // 检查论文状态是否为院级审核状态
        if (!paper.getStatus().equals(StatusCheckConstant.WAIT_COLLEGE_CHECK)) {
            throw new BaseException("只有在院级审核状态的论文才能撤回！");
        }
        
        // 将论文状态改为草稿
        paper.setStatus("草稿");
        
        // 更新论文
        return baseMapper.updateById(paper) == 1;
    }
    
    /**
     * 检查论文字段
     * 验证论文必填字段是否完整
     * @param paper 论文实体
     */
    public void checkPaper(Paper paper) {
        if (Objects.isNull(paper)) {
            throw new BaseException("论文编号有误!");
        }
        if (!paper.getStatus().equals("草稿") && !paper.getStatus().equals("被院级退回") && !paper.getStatus().equals("被校级退回")) {
            throw new BaseException("该论文不适用于该阶段!");
        }

        // 检查各项不可为空选项
        if (StrUtil.isEmpty(paper.getClassifi()) || StrUtil.isBlank(paper.getClassifi())) {
            throw new BaseException("请输入统计分类!");
        }
        if (StrUtil.isEmpty(paper.getSignedUnit()) || StrUtil.isBlank(paper.getSignedUnit())) {
            throw new BaseException("请输入署名单位!");
        }
        if (StrUtil.isEmpty(paper.getPaperName()) || StrUtil.isBlank(paper.getPaperName())) {
            throw new BaseException("请输入论文名称!");
        }
        if (StrUtil.isEmpty(paper.getPeriodicalName()) || StrUtil.isBlank(paper.getPeriodicalName())) {
            throw new BaseException("请输入刊物名称!");
        }
        if (StrUtil.isEmpty(paper.getPeriodicalCate()) || StrUtil.isBlank(paper.getPeriodicalCate())) {
            throw new BaseException("请输入刊物分类!");
        }
        if (StrUtil.isEmpty(paper.getPaperCate()) || StrUtil.isBlank(paper.getPaperCate())) {
            throw new BaseException("请输入论文分类!");
        }
        if (StrUtil.isEmpty(paper.getAnnualVolumePage()) || StrUtil.isBlank(paper.getAnnualVolumePage())) {
            throw new BaseException("请输入年卷期页码!");
        }
        if (StrUtil.isEmpty(paper.getResearchCate()) || StrUtil.isBlank(paper.getResearchCate())) {
            throw new BaseException("请输入研究类别!");
        }
        if (StrUtil.isEmpty(paper.getFirstDiscipline()) || StrUtil.isBlank(paper.getFirstDiscipline())) {
            throw new BaseException("请输入一级学科!");
        }
        if (StrUtil.isEmpty(paper.getSchoolSup()) || StrUtil.isBlank(paper.getSchoolSup())) {
            throw new BaseException("请输入是否受学校经费资助!");
        }
        
        // 检查量化分数是否填写
        Paper_Qualification qualification = iPaperQualificationService.getOne(
                Wrappers.lambdaQuery(Paper_Qualification.class)
                        .eq(Paper_Qualification::getPaperID, paper.getPaperID())
        );
        if (Objects.isNull(qualification)) {
            throw new BaseException("请先填写论文的量化分数!");
        }
        
        // 检查作者列表是否填写
        List<Paperauthor> authorList = iPaperauthorService.list(
                Wrappers.lambdaQuery(Paperauthor.class)
                        .eq(Paperauthor::getPaperID, paper.getPaperID())
        );
        if (CollectionUtils.isEmpty(authorList)) {
            throw new BaseException("请先添加论文的作者信息!");
        }
        
        // 检查是否填写了第一作者（包括第一作者、共同第一作者、第一作者兼通讯作者等）
        boolean hasFirstAuthor = authorList.stream()
                .anyMatch(author -> author.getAuthortype() != null 
                        && author.getAuthortype().contains("第一作者"));
        if (!hasFirstAuthor) {
            throw new BaseException("请先添加论文的第一作者!");
        }
    }
}
